package com.hujiheng.paike.controller;

import com.hujiheng.paike.common.lang.Result;
import com.hujiheng.paike.pojo.Course;
import com.hujiheng.paike.pojo.Teacher;
import com.hujiheng.paike.service.CourseService;
import com.hujiheng.paike.service.TeacherService;
import com.hujiheng.paike.view.TeacherView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private CourseService courseService;

    @RequestMapping("/search/{id}")
    public Result searchById(@PathVariable("id") int teacherId) {
        Teacher byId = teacherService.getById(teacherId);
        if (byId == null) {
            return Result.fail("没有这个老师");
        }
        return Result.success("找到了", byId);
    }

    @RequestMapping("/list")
    public Result list() {
        List<TeacherView> teacherList = teacherService.getTeacherList();
        return Result.success(teacherList);
    }

    @RequestMapping("/edit")
    public Result edit(@Validated @RequestBody TeacherView teacherView) {
        Course courseByName = courseService.getCourseByName(teacherView.getCourseName());
        if (courseByName == null) {
            return Result.fail("课程不存在，请重新输入");
        }
        Teacher teacher = new Teacher(teacherView.getTeacherId(),
                teacherView.getTeacherName(),
                courseByName.getCourseId());
        int updateTeacher = teacherService.updateTeacher(teacher);
        if (updateTeacher < 1) {
            return Result.fail("修改失败");
        }
        System.out.println(updateTeacher);
        return Result.success("修改成功");
    }

    @RequestMapping("/add")
    public Result add(@Validated @RequestBody TeacherView teacherView) {
        Course courseByName = courseService.getCourseByName(teacherView.getCourseName());
        if (courseByName == null) {
            return Result.fail("课程不存在，请重新输入");
        }
        Teacher teacher = new Teacher(teacherView.getTeacherName(),
                courseByName.getCourseId());
        int addTeacher = teacherService.addTeacher(teacher);
        if (addTeacher < 1) {
            return Result.fail("添加失败");
        }
        return Result.success("添加成功");
    }

    @RequestMapping("/del/{teacherId}")
    public Result del(@PathVariable("teacherId") int teacherId) {
        int deleteTeacher = teacherService.deleteTeacher(teacherId);
        if (deleteTeacher < 1) {
            return Result.fail("删除失败");
        }
        return Result.success("删除成功");
    }
}
